# -*- coding: utf-8 -*-
import time

from django.http import JsonResponse
from django.shortcuts import render, redirect, HttpResponse, reverse

from utils.tencent.cos import create_bucket
from web import models
from web.forms.project import ProjectForm


def project_list(request):
    """项目列表"""
    
    if request.method == 'GET':
        
        # 1. 获取项目
        # 筛选数据：星标，未星标，加入
        project_dict = {'star': [], 'my': [], 'join': []}
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({'value': row, 'type': 'my'})
            else:
                project_dict['my'].append(row)
        
        join_project_list = models.Participant.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'my'})
            else:
                project_dict['join'].append(item.project)
        
        form = ProjectForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})
    
    form = ProjectForm(request, data=request.POST)
    if form.is_valid():
        project_name = form.cleaned_data['project_name']
        # 1. 创建一个cos桶,名字不能重复：
        bucket = '{}-1302759476'.format(project_name, str(int(time.time())))
        region = 'ap-nanjing'
        create_bucket(bucket, region)
        
        # 3. 验证通过: 项目名，颜色，描述
        form.instance.bucket = bucket
        form.instance.region = region
        form.instance.creator = request.tracer.user
        # 4. 创建项目
        instance = form.save()
        
        # 5. 初始化问题类型
        issues_type_obj_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_obj_list.append(models.IssuesType(project=instance, title=item))
        # 批量创建
        models.IssuesType.objects.bulk_create(issues_type_obj_list)
        
        return JsonResponse({'status': True})
        
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """处理星标"""
    if project_type == 'my':
        # 更新 加上creator=reqeust.tracer.user，防止用户在地址栏输入别人的项目id
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        
        # 重定向
        return redirect(reverse('web:project_list'))
    
    elif project_type == 'join':
        models.Participant.objects.filter(project_id=project_id, creator=request.tracer.user).update(star=True)
        return redirect(reverse('web:project_list'))
    
    return HttpResponse('error')


def project_unstar(request, project_type, project_id):
    """取消星标"""

    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)

        return redirect(reverse('web:project_list'))
    elif project_type == 'join':
        models.Participant.objects.filter(project_id=project_id, creator=request.tracer.user).update(star=False)
        return redirect(reverse('web:project_list'))

    return HttpResponse('error')
